package run.yiqi.blog;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import run.yiqi.blog.dao.EndUserDao;
import run.yiqi.blog.model.EndUser;
import run.yiqi.blog.service.EmailService;
import run.yiqi.blog.vo.EmailVo;
import run.yiqi.util.StringUtil;

@Slf4j
@Component
@Order(value = 1)
public class InitDatabase implements CommandLineRunner {

    @Autowired
    @Lazy
    private EndUserDao endUserDao;

    @Autowired
    @Lazy
    private SqlDao sqlDao;
    
    @Lazy @Autowired
    private EmailService emailService;

    @Override
    public void run(String... args) throws Exception {
        long c = endUserDao.count();
        if (c == 0) {
            ClassPathResource cpr = new ClassPathResource("init.sql");
            @Cleanup
            InputStreamReader isr = new InputStreamReader(cpr.getInputStream(), "UTF-8");
            @Cleanup
            BufferedReader br = new BufferedReader(isr);
            List<String> sqls = new ArrayList<String>();

            String sql = null;
            while ((sql = br.readLine()) != null) {
                if (sql.startsWith("--") || StringUtil.isEmpty(sql.trim())) {
                    continue;
                }
                sqls.add(sql);
            }
            this.sqlDao.executeSql(sqls);
            
            this.email();
        }
        
    }

    private void email() {
        List<EndUser> endUsers = this.endUserDao.findAll();

        endUsers.forEach(endUser -> {
            EmailVo emailVo = new EmailVo();
            emailVo.getTos().add(endUser.getEmail());
            emailVo.setSubject("[Issue Tracking] Your Account Created.");
            //默认密码都是admin, 用户要修改
            StringBuffer msg = new StringBuffer("");
            msg.append("Dear ").append(endUser.getUsername()).append(": ");
            msg.append("<br/>Your account: ").append(endUser.getUsername()).append(" / ").append("admin");
            msg.append("<br/>Please click <a href='").append(this.emailService.getDeployUrl()).append("'>here</a> to login the system.");
            emailVo.setContent(msg.toString());

            try {
                emailService.sendEmail(emailVo);
            } catch (EmailException e) {
                log.info("Mail Failed: " + e.getMessage());
            }
        });
    }

}

@Component
class SqlDao {
    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public void executeSql(List<String> sqls) throws Exception {
        sqls.forEach(sql -> {
            Query query = entityManager.createNativeQuery(sql);
            query.executeUpdate();
        });
    }

}
